package lego.jbv;

import lego.jbv.CarCommand.Command;
import lejos.nxt.Button;
import lejos.nxt.LCD;
import lejos.nxt.LightSensor;
import lejos.nxt.SensorPort;

class Line extends Thread implements ICommand
{	
	private boolean stop;
	private CarCommand.Command command;
	private boolean hasCommand;
	private LightSensor left;
	private LightSensor right;
	private int lightLeft;
	private int lightRight;
	private int threshold;
	
    public Line()
    {
    	this.setDaemon(true);
    	hasCommand = false;
    	
    	left = new LightSensor(SensorPort.S4);
    	right = new LightSensor(SensorPort.S1);
    	
    	left.setFloodlight(true);
    	right.setFloodlight(true);
    }
    
	public void run() 
    {				       
		while(!stop)
		{
			lightLeft = left.readValue();
			lightRight = right.readValue();
			
			//White to the left and black to the right
			if(lightLeft > threshold && lightRight <= threshold)
			{
				command = Command.RIGHT;
			}
			
			//Black to the left and white to the right
			else if(lightLeft <= threshold && lightRight > threshold)
			{
				command = Command.LEFT;
			}
		}
    }
	
	public void stop()
	{
		stop = true;
	}
	
	public void calibrate()
	{
		LCD.clear();
		LCD.drawString("Place the light", 0, 0);
		LCD.drawString("sensors on black", 0, 1);
		LCD.drawString("and press OK.", 0, 0);
		
		Button.waitForAnyPress();
		
		threshold = (int)((left.readValue()+right.readValue())/2)+10;
		
		LCD.clear();
		LCD.drawString("Calibration complete", 0, 0);
		
		Button.waitForAnyPress();
	}

	@Override
	public Command getCommand() {
		return command;
	}

	@Override
	public boolean hasCommand() {
		return hasCommand;
	}
}


